import _ from 'lodash';
import { useState } from 'react';
import tagsApis from '../../apis/tags';
import { toastError } from '../toast-error';
import AutoComplete from '../ui/AutoComplete';
import Tag from '../ui/Tag';

type TagSelectProps = {
  domain: number;
  value: SimpleTag[];
  onChange: (tags: SimpleTag[]) => void;
};

export default function TagSelect({ domain, value, onChange }: TagSelectProps) {
  const [tagsToSelect, setTagsToSelect] = useState<SimpleTag[]>([]);

  const search = (p: string) =>
    tagsApis
      .searchByPrefix(domain, p)
      .then((it) => {
        setTagsToSelect(it);
      })
      .catch((err) => toastError(err));

  const create = (name: string) =>
    tagsApis
      .create(domain, name)
      .then((it) => {
        onChange([...value, it]);
        setTagsToSelect([]);
      })
      .catch((err) => toastError(err));

  return (
    <div className="inline-flex items-center gap-1">
      {value.map((it) => (
        <Tag key={it.id} closable onClose={() => onChange(_.filter(value, (t) => t.id != it.id))}>
          {it.name}
        </Tag>
      ))}
      <AutoComplete
        items={tagsToSelect}
        toId={(it) => it.id + ''}
        itemToString={(it) => it.name}
        onChange={(it) => search(it)}
        onSelect={(it) => {
          if (it) onChange(_.uniqBy([...value, it], 'id'));
        }}
        onEnter={(it) => create(it)}
        placeholder="添加标签"
      />
    </div>
  );
}
